//
//  YHEmoticonKeyboard.swift
//  YHWeibo
//
//  Created by yuhao.mac on 16/7/4.
//  Copyright © 2016年 yuhao.mac. All rights reserved.
//

import UIKit

class YHEmoticonKeyboard: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        addSubview(toolBar)
        addSubview(pageView)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(self)
            make.height.equalTo(37)
        }
        
        pageView.snp_makeConstraints { (make) -> Void in
            make.left.top.right.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        toolBar.toolBarClosure = {[weak self] (type:YHEmoticonToolBarType)->() in
            
            //创建indexpath
            let indexPath = NSIndexPath(forItem: 0, inSection: type.rawValue)
            
            self?.pageView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        }
    }
    
    lazy var toolBar:YHEmoticonToolbar = YHEmoticonToolbar()
    
    //表情键盘
    private lazy var pageView: YHEmoticonPageView = {
        let view = YHEmoticonPageView()
        //设置代理
        view.delegate = self
        //取消谈话效果
        view.bounces = false
        //分页
        view.pagingEnabled = true
        //隐藏滚动条
        view.showsHorizontalScrollIndicator = false
        view.showsVerticalScrollIndicator = false
        return view
        
    }()

}

extension YHEmoticonKeyboard:UICollectionViewDelegate{
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //获取当前屏幕键盘view的中心点
        let centerX = SCREENW / 2 + scrollView.contentOffset.x
        
        //获取当前屏幕显示的cell并重新排序
        let cellArray = pageView.visibleCells().sort { (cell1, cell2) -> Bool in
            return cell1.frame.origin.x < cell2.frame.origin.x
        }
        
        //当屏幕显示出两个cell的时候我们才做判断
        if cellArray.count == 2{
            
            //获取显示多的cell的indexPath
            var indexPath:NSIndexPath
            
            let firstCell = cellArray.first!
            let lastCell = cellArray.last!
            
            if firstCell.frame.contains(CGPoint(x: centerX, y: 0)){
                indexPath = pageView.indexPathForCell(firstCell)!
            }else{
                indexPath = pageView.indexPathForCell(lastCell)!
            }
            
            //滚动pageView 改变toolBar按钮的选中状态
            toolBar.setCurrentButtons(indexPath.section)
        }
    }
}







